<template>
  <div class="article-edit">
    <div class="header">
      <h1>{{ isEdit ? '编辑文章' : '新建文章' }}</h1>
    </div>
    
    <a-form
      :model="articleForm"
      layout="vertical"
    >
      <a-form-item label="标题" required>
        <a-input v-model:value="articleForm.title" placeholder="请输入文章标题" />
      </a-form-item>
      
      <a-form-item label="摘要">
        <a-textarea v-model:value="articleForm.summary" placeholder="请输入文章摘要" :rows="3" />
      </a-form-item>
      
      <a-form-item label="分类">
        <a-select
          v-model:value="articleForm.categoryId"
          placeholder="请选择分类"
          style="width: 200px"
        >
          <a-select-option v-for="category in categoryStore.categoryList" :key="category.id" :value="category.id">
            {{ category.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      
      <a-form-item label="封面图片">
        <div class="upload-wrapper">
          <a-upload
            list-type="picture-card"
            :file-list="fileList"
            :customRequest="handleUpload"
            :maxCount="1"
            v-if="!articleForm.coverImage"
          >
            <div v-if="!articleForm.coverImage">
              <plus-outlined />
              <div style="margin-top: 8px">上传</div>
            </div>
          </a-upload>
          <div v-if="articleForm.coverImage" class="preview-image">
            <img :src="getStaticUrl(articleForm.coverImage)" alt="封面预览" />
            <div class="preview-actions">
              <a-button type="primary" danger size="small" @click="removeCoverImage">删除</a-button>
            </div>
          </div>
        </div>
      </a-form-item>
      
      <a-form-item label="内容" required>
        <div id="editor-container" ref="editorContainer"></div>
      </a-form-item>
      
      <a-form-item label="状态">
        <a-radio-group v-model:value="articleForm.status">
          <a-radio :value="0">草稿</a-radio>
          <a-radio :value="1">发布</a-radio>
        </a-radio-group>
      </a-form-item>
      
      <a-form-item>
        <a-button type="primary" @click="handleSubmit">保存</a-button>
        <a-button style="margin-left: 10px" @click="handleCancel">取消</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { useArticleStore } from '@/stores/article';
import { useCategoryStore } from '@/stores/category';
import { getArticleDetail } from '@/api/article';
import Quill from 'quill';
import 'quill/dist/quill.snow.css';
import { uploadImage } from '@/api/upload';
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css';
import QuillBetterTable from 'quill-better-table';
import 'quill-better-table/dist/quill-better-table.css';
import { getStaticUrl } from '@/utils/url';
// 注册代码高亮
hljs.configure({
  languages: ['javascript', 'typescript', 'python', 'java', 'html', 'css', 'bash', 'json', 'sql']
});

const route = useRoute();
const router = useRouter();
const articleStore = useArticleStore();
const categoryStore = useCategoryStore();
const editorContainer = ref(null);
let quillEditor = null;

const isEdit = computed(() => route.params.id !== undefined);

const articleForm = ref({
  id: null,
  title: '',
  summary: '',
  content: '',
  categoryId: undefined,
  coverImage: '',
  status: 0
});

const fileList = ref([]);

// 初始化编辑器
const initQuillEditor = () => {
  if (!editorContainer.value) return;
  
  // 注册表格模块
  Quill.register({
    'modules/better-table': QuillBetterTable
  }, true);

  // 工具栏配置
  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],
    ['blockquote', 'code-block'],
    [{ 'header': 1 }, { 'header': 2 }],
    [{ 'list': 'ordered' }, { 'list': 'bullet' }],
    [{ 'script': 'sub' }, { 'script': 'super' }],
    [{ 'indent': '-1' }, { 'indent': '+1' }],
    [{ 'direction': 'rtl' }],
    [{ 'size': ['small', false, 'large', 'huge'] }],
    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
    [{ 'color': [] }, { 'background': [] }],
    [{ 'font': [] }],
    [{ 'align': [] }],
    ['clean'],
    ['link', 'image', 'video'],
    ['table']
  ];

  // 创建编辑器实例
  quillEditor = new Quill(editorContainer.value, {
    modules: {
      toolbar: toolbarOptions,
      syntax: {
        hljs: hljs
      },
      'better-table': {
        operationMenu: {
          items: {
            unmergeCells: {
              text: '拆分单元格'
            }
          }
        }
      }
    },
    theme: 'snow'
  });

  // 添加表格按钮事件
  const toolbar = quillEditor.getModule('toolbar');
  toolbar.addHandler('table', () => {
    const tableModule = quillEditor.getModule('better-table');
    tableModule.insertTable(3, 3);
  });

  // 图片上传处理
  toolbar.addHandler('image', () => {
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');
    input.click();

    input.onchange = async () => {
      const file = input.files?.[0];
      if (!file) return;

      try {
        const formData = new FormData();
        formData.append('file', file);
        
        const res = await uploadImage(formData);
        const url = res.url;
        
        // 获取光标位置并插入图片
        const range = quillEditor.getSelection();
        quillEditor.insertEmbed(range.index, 'image', getStaticUrl(url));
      } catch (error) {
        console.error('图片上传失败:', error);
        message.error('图片上传失败');
      }
    };
  });

  // 在text-change事件中处理代码块
  quillEditor.on('text-change', () => {
    // 处理代码块
    const codeBlocks = document.querySelectorAll('.ql-code-block');
    codeBlocks.forEach(block => {
      try {
        hljs.highlightElement(block);
      } catch (e) {
        console.error('代码高亮错误:', e);
      }
    });
  });
};

// 获取文章详情
const fetchArticleDetail = async (id) => {
  try {
    const article = await getArticleDetail(id);
    
    // 填充表单数据
    articleForm.value.id = article.id;
    articleForm.value.title = article.title;
    articleForm.value.summary = article.summary || '';
    articleForm.value.categoryId = article.categoryId;
    articleForm.value.coverImage = article.coverImage;
    articleForm.value.status = article.status;
    
    // 设置编辑器内容
    if (quillEditor && article.content) {
      quillEditor.root.innerHTML = article.content;
    }
    
    // 如果有封面图片，设置预览
    if (article.coverImage) {
      fileList.value = [
        {
          uid: '-1',
          name: 'cover.jpg',
          status: 'done',
          url: getStaticUrl(article.coverImage)
        }
      ];
    }
  } catch (error) {
    console.error('获取文章详情失败:', error);
    message.error('获取文章详情失败');
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!articleForm.value.title) {
    message.error('请输入文章标题');
    return;
  }
  
  if (!quillEditor) {
    message.error('编辑器初始化失败');
    return;
  }
  
  // 获取编辑器内容
  const content = quillEditor.root.innerHTML;
  if (!content || content === '<p><br></p>') {
    message.error('请输入文章内容');
    return;
  }
  
  try {
    // 准备提交的数据
    const articleData = {
      ...articleForm.value,
      content
    };
    
    // 保存文章
    await articleStore.saveArticle(articleData);
    message.success('保存成功');
    router.push('/article/list');
  } catch (error) {
    console.error('保存文章失败:', error);
    message.error('保存文章失败');
  }
};

// 取消编辑
const handleCancel = () => {
  router.push('/article/list');
};

// 上传封面图片
const handleUpload = async ({ file }) => {
  try {
    const formData = new FormData();
    formData.append('file', file);
    
    const res = await uploadImage(formData);
    articleForm.value.coverImage = res.url;
    
    message.success('封面图片上传成功');
  } catch (error) {
    console.error('封面图片上传失败:', error);
    message.error('封面图片上传失败');
  }
};

// 删除封面图片
const removeCoverImage = () => {
  articleForm.value.coverImage = '';
  fileList.value = [];
};

// 组件挂载时初始化
onMounted(async () => {
  // 获取分类列表
  await categoryStore.getCategoryList();
  
  // 初始化编辑器
  await nextTick();
  initQuillEditor();
  
  // 如果是编辑模式，获取文章详情
  if (isEdit.value && route.params.id) {
    const id = parseInt(route.params.id.toString());
    await fetchArticleDetail(id);
  }
});
</script>

<style>
.article-edit {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

#editor-container {
  height: 500px;
  margin-bottom: 20px;
}

.upload-wrapper {
  display: flex;
  align-items: center;
}

.preview-image {
  width: 200px;
  position: relative;
}

.preview-image img {
  width: 100%;
  border-radius: 4px;
}

.preview-actions {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: none;
}

.preview-image:hover .preview-actions {
  display: block;
}

.preview-image:hover::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 4px;
}

/* 苹果风格代码块样式 */
.ql-syntax.apple-style-code {
  position: relative;
  background-color: #282c34;
  color: #abb2bf;
  border-radius: 6px;
  padding: 16px;
  margin: 8px 0;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
  font-size: 14px;
  line-height: 1.5;
  overflow: auto;
  white-space: pre;
}

/* 表格样式 */
.ql-better-table td {
  border: 1px solid #ccc;
  padding: 6px 13px;
}

.ql-better-table th {
  border: 1px solid #ccc;
  padding: 6px 13px;
  background-color: #f0f0f0;
  font-weight: bold;
}
</style> 